//
//  PEHiSolarSettingVC.m
//  PrivateApp
//
//  Created by Yan Chen on 2025/6/30.
//

#import "RHHiSolarSettingVC.h"
#import "SYChartTool.h"
#import "ZYSwitch.h"
#import "KWTMGRNSettingSyncVC.h"
#import "SettingOptionController.h"
#import "RHDeviceModel.h"
#import "RHEndPointModel.h"
#import "PasswordVerifyController.h"
#import "RHTools.h"

#import "RHHiSolarSettingChgTimeCell.h"
#import "KWTHiSolarSettingEditTimeVC.h"
#import "WSDatePickerView.h"
#import "NetworkAgent.h"
#import "RHVppSetCommonModel.h"
#import "JCDataConvert.h"

@interface RHHiSolarSettingVC ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *dataArr;

@property (nonatomic ,strong) NSMutableArray *paraSectionArr;//每组的参数

@property (nonatomic ,assign) NSInteger paraIndex;//参数下标

@property (nonatomic, strong) NSArray *syncArr;//要同步的设备   deviceId

@property (nonatomic, strong) MBProgressHUD *hud;

@property (nonatomic ,strong)  RHDeviceModel *deviceModel;

@property (nonatomic ,strong) RHEndPointModel *endPointModel;
@end

@implementation RHHiSolarSettingVC

-(instancetype)initWithDeviceModel:(RHDeviceModel*)deviceModel endpoint:(RHEndPointModel*)endpointModel
{
    if (self = [super init]) {
        _deviceModel = deviceModel;
        _endPointModel = endpointModel;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"充放电配置".rh_localized;
    self.paraSectionArr = [NSMutableArray array];
    [self setupUI];
    [self getParamStatusData];
}

- (void)setupUI{
    kWeakSelf;
    NSArray *arr = [SYChartTool loadJsonFileWithName:@"setting_ao_HiSolar_chg"];
    self.dataArr = [NSArray yy_modelArrayWithClass:[RHVppSetCommonModel class] json:arr];
    
    if (self.deviceArr.count>1) {
        UIBarButtonItem *syncBtn = [UIBarButtonItem itemWithImage:@"setting_sync" ImageHighLight:@"setting_sync" Target:self Seletor:@selector(showSyncTip) CGRect:CGRectMake(0, 0, 40, 40)];
        self.navigationItem.rightBarButtonItems = @[syncBtn];
    }
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];

    [_tableView registerClass:[RHHiSolarSettingChgTimeCell class] forCellReuseIdentifier:@"RHHiSolarSettingChgTimeCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    _tableView.tableFooterView = [self footerView];
    [self.view addSubview:_tableView];
     
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.mas_offset(0);
        make.top.mas_offset(0);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    [self.tableView addHeaderRefresh:^{
        [weakSelf getParamStatusData];
    }];
    
    
}

-(void)showSyncTip
{
    kWeakSelf;
    QMUIAlertController *alertVC = [QMUIAlertController alertControllerWithTitle:@"同步其他设备?".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
    QMUIAlertAction *cancel = [QMUIAlertAction actionWithTitle:@"取消".rh_localized style:QMUIAlertActionStyleCancel handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {

    }];
    QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [weakSelf syncOtherDevice];
    }];
    [alertVC addAction:cancel];
    [alertVC addAction:sure];
    [alertVC showWithAnimated:YES];
}

#pragma mark --------- 同步设置其他设备
-(void)syncOtherDevice
{

//    KWTMGRNSettingSyncVC *syncVC = [[KWTMGRNSettingSyncVC alloc]init];
//    syncVC.deviceModel = self.deviceModel;
//    syncVC.totalDevArr = self.deviceArr.mutableCopy;
//    syncVC.dataArr = self.dataArr;
//    kWeakSelf;
//    syncVC.selectBlock = ^(NSArray * syncArr) {
//        weakSelf.syncArr = syncArr;
//    };
//    [self.navigationController pushViewController:syncVC animated:YES];
    
    //直接同步,不选择设备
    NSMutableArray *tempArr = [NSMutableArray array];
    [self.deviceArr enumerateObjectsUsingBlock:^(RHDeviceModel*  _Nonnull device, NSUInteger idx, BOOL * _Nonnull stop) {
        if (![device.deviceId isEqualToString:self.deviceModel.deviceId]) {
            [tempArr addObject:device.deviceId];
        }
        
    }];
    self.syncArr = tempArr.copy;
    [self checkParaEnableStatus];
}

#pragma mark ------ 3.获取参数值
-(void)getParamStatusData
{
    
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getParamStatusData argument:@{@"deviceId":ValidNullData(self.deviceModel.deviceId),@"sn":ValidNullData(self.endPointModel.sn)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            NSDictionary *deviceInfo = request.responseJSONObject[@"data"];
            NSMutableDictionary *mtbDic = deviceInfo.mutableCopy;
            //强制显示 高级工作模式为放电优先 ,TOU时间使能打开
            [mtbDic setObject:@"1" forKey:@"Inv3_AdvaMode"];
            [mtbDic setObject:@"1" forKey:@"Inv3_TOUEn"];
            
            [self readDefult:mtbDic];
            [self.tableView reloadData];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        
    }];
}

//读取默认值
- (void)readDefult:(NSDictionary *)dic{
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
       
        [model readHiSolarDefult:dic];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        return 20;
    }
    
    return 60;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0||section == 1) {
        UIView *headV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 20)];
        headV.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 10, kUI_WINDOW_W-30, 10)];
        bgView.backgroundColor = UIColor.whiteColor;
        bgView.layer.cornerRadius = 8;
        bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
        bgView.layer.masksToBounds = YES;
        [headV addSubview:bgView];
        return headV;
    }
    
    UIView *headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 60)];
    headerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
    RHVppSetCommonModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 15, kUI_WINDOW_W-30, 45)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMinYCorner|kCALayerMaxXMinYCorner;
    bgView.layer.masksToBounds = YES;
    [headerView addSubview:bgView];
    
    QMUILabel *titleLab = [QMUILabel labelWithText:sectionModel.sectionTitle.rh_localized font:kSYSTEMFONT(16) textColor:kCOLOR_HEX(@"#171A1D")];
    [bgView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.centerY.mas_offset(0);
    }];
    
    
    UIView *line = kView;
    line.backgroundColor = kCOLOR_HEX_A(@"#7E868E",0.2);
    [bgView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.height.offset(1);
    }];
    
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    
    return 10;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    kWeakSelf;
    UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    footerView.backgroundColor = kCOLOR_HEX(@"#F0F5FF");
//    PEVppSetCommonModel *sectionModel = self.dataArr[section];
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(15, 0, kUI_WINDOW_W-30, 10)];
    bgView.backgroundColor = UIColor.whiteColor;
    bgView.layer.cornerRadius = 8;
    bgView.layer.maskedCorners = kCALayerMinXMaxYCorner|kCALayerMaxXMaxYCorner;
    bgView.layer.masksToBounds = YES;
    [footerView addSubview:bgView];
    
    
    return footerView;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    RHVppSetCommonModel *sectionModel = self.dataArr[section];
    return sectionModel.rows.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    RHVppSetCommonModel *sectionModel = self.dataArr[indexPath.section];
    RHVppSetCommonModel *rowModel = sectionModel.rows[indexPath.row];
    if ([rowModel.type isEqualToString:@"time"]) {//充放电时段设置
        RHHiSolarSettingChgTimeCell *settingCell = [tableView dequeueReusableCellWithIdentifier:@"RHHiSolarSettingChgTimeCell"];
        rowModel.rowTitle = [NSString stringWithFormat:@"%@ %ld",@"时段".rh_localized,indexPath.row+1];
        settingCell.model = rowModel;
        kWeakSelf;
        settingCell.selectAction = ^(RHVppSetCommonModel * _Nonnull model) {
            [weakSelf editChargeDischargeInfo:model index:indexPath.row+1];
        };
        settingCell.commitAction = ^(RHVppSetCommonModel * _Nonnull model) {
            [weakSelf checkParaEnableStatus];
        };
        settingCell.readAction = ^(RHVppSetCommonModel * _Nonnull model) {
            [weakSelf readParamData];
        };
        return settingCell;
    }
    return [UITableViewCell new];
}

#pragma mark -------- 充放电时间段选择
-(void)editChargeDischargeInfo:(RHVppSetCommonModel*)model index:(NSInteger)index
{
    kWeakSelf;
    KWTHiSolarSettingEditTimeVC *editVC = [[KWTHiSolarSettingEditTimeVC alloc]init];
    editVC.index = index;
    editVC.model = model;
    editVC.sureBlock = ^{
        [weakSelf.tableView reloadData];
    };
    [self.navigationController pushViewController:editVC animated:YES];
}

#pragma mark -------- 选择时间
- (void)dateAction:(RHVppSetCommonModel *)settingModel  {
    
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:DateStyleShowYearMonthDayHourMinuteSecond CompleteBlock:^(NSDate *selectDate) {
        NSString *dateFormatStr = @"yyyy/MM/dd HH:mm:ss";
        NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];
        settingModel.content = currentDate;
        [self.tableView reloadData];
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    [datePickerV show];
}

#pragma mark ------ 选择
-(void)selectAction:(RHVppSetCommonModel*)model
{
    kWeakSelf;
    SettingOptionController *vc = [[SettingOptionController alloc] initWithData:model.selectList];
    [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
    vc.curTextValue = [model.content integerValue];
   
    vc.selectBlock = ^(NSInteger index) {
        DevSettingOptionModel *select_model = model.selectList[index];
        model.enumText = select_model.text;//存要显示的内容
        model.content = [NSString stringWithFormat:@"%ld",select_model.textValue];//存下标
        [weakSelf.tableView reloadData];
    };
}


#pragma mark -------- 提交参数前 判断相关使能是否打开
-(void)checkParaEnableStatus
{
    //工作模式没有禁用,电网充电使能,TOU时间使能要打,时间设置才能生效
//    if (self.paraSetValid==NO) {
//        kWeakSelf;
//        QMUIAlertController *alertVC = [[QMUIAlertController alloc]initWithTitle:@"高级工作模式要启用,电网充电使能和TOU时间控制使能要打开,时间设置才能生效!".rh_localized message:nil preferredStyle:QMUIAlertControllerStyleAlert];
//        QMUIAlertAction *sure = [QMUIAlertAction actionWithTitle:@"确定".rh_localized style:QMUIAlertActionStyleDefault handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
//            [weakSelf commitAction];
//        }];
//        [alertVC addAction:sure];
//        [alertVC showWithAnimated:YES];
//    }else{
        [self commitAction];
//    }
}

#pragma mark -------- 提交参数前 密码校验
-(void)commitAction
{
   
    if (Password_Check) {
        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
        
        kWeakSelf;
        vc.callBackBlock = ^(NSString * _Nonnull password) {
                    NSDictionary *dic = [RHTools getAccountInfo];
                    if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
                        BOOL result = [weakSelf createSectionSetPara];
                        if (result == NO) return;//校验不过
                        [weakSelf.hud hideAnimated:NO];
                        [weakSelf showHud];
                        [weakSelf devParamsSetFromNetwork];
                    }else{
                        [QMUITips showInfo:@"密码错误".rh_localized];
                    }
        };
    }else{
        BOOL result = [self createSectionSetPara];
        if (result == NO) return;//校验不过
        [self.hud hideAnimated:NO];
        [self showHud];
        [self devParamsSetFromNetwork];
    }
    
    
}

//把设置指令分组下发   没有值的参数不下发
-(BOOL)createSectionSetPara
{
    self.paraIndex = 0;
    [self.paraSectionArr removeAllObjects];
  
    __block BOOL isCheckOK = YES;//校验是否通过
    
    //充电使能和放电使能的值
    NSMutableString *enableValue = [NSMutableString string];
    
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *paraListArr = [NSMutableArray array];
        
        //上一时间段的结束时间,如果有就比较(当前时间段的开始时间要大于上一段的结束时间)
        __block NSString* lastEndTime;
        __block NSInteger lastEndTimeIndex = 0;
        
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger rowIdx, BOOL * _Nonnull stop_row) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                if (rowModel.content.length == 0) {
                    return;
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:rowModel.content forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                
                [paraListArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
                NSMutableArray *itemParaArr = [NSMutableArray array];
                
                __block NSString *t_value = @"";//充电使能的值
                
                __block NSString *startTime;//每段的开始时间
                __block NSString *endTime;  //每段的结束时间
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (itemModel.content.length == 0) {
                        return;
                    }
                    
                    //开关状态
                    if ([itemModel.type isEqualToString:@"select"]) {
                        [enableValue insertString:ValidNullDataToString(itemModel.content, @"0") atIndex:0];
                        return;
                    }
                    
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:itemModel.content forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    
                    //待机 设置成1
                    NSString *chgKey = [NSString stringWithFormat:@"Inv5_VM%ld",rowIdx+1];
                    if ([itemModel.key isEqualToString:chgKey]) {
                        if ([itemModel.content isEqualToString:@"2"]) {
                            [itemDic setObject:@"1" forKey:@"value"];
                        }
                    }
                    
                    [itemParaArr addObject:itemDic];
                    
                    //判断结束时间是否大于开始时间
                    NSString *startTime_key = [NSString stringWithFormat:@"Inv5_VTS%zd",rowIdx+1];
                    NSString *endTime_key   = [NSString stringWithFormat:@"Inv5_VTE%zd",rowIdx+1];
                    if ([itemModel.key isEqualToString:startTime_key]&&itemModel.content.length>0) {
                        startTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        RHVppSetCommonModel  *endTimeModel = [rowModel.items safeObjectAtIndex:idx+1];
                        if ([endTimeModel.key isEqualToString:endTime_key]&&endTimeModel.content.length>0) {
                            //结束时间
                            endTime = [endTimeModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        }
                        //判断当前开始时间是否大于上一段结束时间 如果两个是00:00的话不判断
                        BOOL bothZero = ([startTime integerValue]==0)&&([endTime integerValue]==0);
                        if (startTime.length>0 && lastEndTime.length>0) {
                            if (([startTime integerValue]<[lastEndTime integerValue])&&(!bothZero)) {
                                [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld开始时间必须大于或等于时段%ld结束时间".rh_localized,rowIdx+1,lastEndTimeIndex+1]];
                                isCheckOK = NO;
                                return;
                            }
                        }
                        
                    }
                    if ([itemModel.key isEqualToString:endTime_key]&&itemModel.content.length>0) {
                        endTime = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        //上一段时间是00:00 - 00:00的话不比较
                        if ([endTime integerValue] != 0) {
                            lastEndTime = endTime;//保存上一时间段的结束时间(有时的情况下)
                            lastEndTimeIndex = rowIdx;
                        }
                    }
                    
                    
                    
                    
                }];
                if (itemParaArr.count>0) {
                    [self.paraSectionArr addObject:itemParaArr];
                }
                
                if (startTime || endTime) {//如果一组里有一个时间填了,就比较,都没填的话不比较 00:00不比较
                    if ([endTime integerValue] <= [startTime integerValue] && ([endTime integerValue] != 0 && [startTime integerValue] != 0)) {
                        isCheckOK = NO;
                        [QMUITips showInfo:[NSString stringWithFormat:@"时段%ld结束时间必须大于开始时间".rh_localized,rowIdx+1]];
                        *stop_row = YES;
                    }
                }
            }
            
        }];
        
        
        
        if (paraListArr.count>0) {
            [self.paraSectionArr addObject:paraListArr];
        }
        
    }];
    
    //校验不通过不提交
    if (isCheckOK == NO) {
        return NO;
    }

    //针对充放电使能冲突的问题,所有的使能组合成一个字段下发
    NSInteger decimalValue = [JCDataConvert ConvertBinaryStringToDecimal:enableValue];
    NSString *value = [NSString stringWithFormat:@"%ld",decimalValue];
    NSDictionary *enableDic = @{
        @"dataType":@"int",
        @"paramName":@"Inv5_VM",
        @"value":value,
        @"regAddr":@(7224),
        @"num":@(16),
        @"offset":@(0),
    };
    
    
    //---------两帧下发------
    if (self.paraSectionArr.count > 4) {
        NSMutableArray *mtbArr_1 = [NSMutableArray array];
        NSMutableArray *mtbArr_2 = [NSMutableArray array];
        
        [self.paraSectionArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull dicArr, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx<3) {
                [mtbArr_1 addObjectsFromArray:dicArr];
            }else{
                [mtbArr_2 addObjectsFromArray:dicArr];
            }
            
        }];
        //将组合的使能值加到第二组中
        [mtbArr_2 addObject:enableDic];
        
        [self.paraSectionArr removeAllObjects];
        [self.paraSectionArr addObject:mtbArr_1];
        [self.paraSectionArr addObject:mtbArr_2];
    }
    
    return YES;
}

//把设置指令分组下发   没有值的参数传0
-(void)createSectionReadPara
{
    self.paraIndex = 0;
    [self.paraSectionArr removeAllObjects];
    [self.dataArr enumerateObjectsUsingBlock:^(RHVppSetCommonModel*  _Nonnull sectionModel, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableArray *paraListArr = [NSMutableArray array];
        [sectionModel.rows enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull rowModel, NSUInteger idx, BOOL * _Nonnull stop) {
            //系统设置不提交(单独提交)
            if ([rowModel.type isEqualToString:@"date"]) {
                return;
            }
            //工作模式 充电使能
            if ([rowModel.type isEqualToString:@"switch"]||[rowModel.type isEqualToString:@"select"]) {
                NSString *value = rowModel.content;
                if (rowModel.content.length == 0) {
                    value = @"0";
                }
                NSMutableDictionary *textDic = [NSMutableDictionary dictionary];
                [textDic setObject:rowModel.format forKey:@"dataType"];
                [textDic setObject:rowModel.key forKey:@"paramName"];
                [textDic setObject:value forKey:@"value"];
                [textDic setObject:@(rowModel.regAddr) forKey:@"regAddr"];
                [textDic setObject:@(rowModel.num) forKey:@"num"];
                [textDic setObject:@(rowModel.offset) forKey:@"offset"];
                [paraListArr addObject:textDic];
            }
            
            //时间段设置
            if ([rowModel.type isEqualToString:@"time"]) {
                NSMutableArray *itemParaArr = [NSMutableArray array];
                [rowModel.items enumerateObjectsUsingBlock:^(RHVppSetCommonModel * _Nonnull itemModel, NSUInteger idx, BOOL * _Nonnull stop) {
                    NSString *value = itemModel.content;
                    if (itemModel.content.length == 0) {
                        value = @"0";
                    }
                    NSMutableDictionary *itemDic = [NSMutableDictionary dictionary];
                    [itemDic setObject:itemModel.format forKey:@"dataType"];
                    [itemDic setObject:itemModel.key forKey:@"paramName"];
                    [itemDic setObject:value forKey:@"value"];
                    [itemDic setObject:@(itemModel.regAddr) forKey:@"regAddr"];
                    [itemDic setObject:@(itemModel.num) forKey:@"num"];
                    [itemDic setObject:@(itemModel.offset) forKey:@"offset"];
                    
                    //时间
                    if ([itemModel.type isEqualToString:@"date"]) {
                        NSString *content = [itemModel.content stringByReplacingOccurrencesOfString:@":" withString:@""];
                        [itemDic setObject:ValidNullData(content) forKey:@"value"];
                    }
                    [itemParaArr addObject:itemDic];
                }];
                if (itemParaArr.count>0) {
                    [self.paraSectionArr addObject:itemParaArr];
                }
                
            }
            
        }];
        if (paraListArr.count>0) {
            [self.paraSectionArr addObject:paraListArr];
        }
        
    }];
    
    //把命令拆成两组下发,节省时间
    if (self.paraSectionArr.count > 4) {
        NSMutableArray *mtbArr_1 = [NSMutableArray array];
        NSMutableArray *mtbArr_2 = [NSMutableArray array];
        
        [self.paraSectionArr enumerateObjectsUsingBlock:^(NSArray*  _Nonnull dicArr, NSUInteger idx, BOOL * _Nonnull stop) {
            if (idx<3) {
                [mtbArr_1 addObjectsFromArray:dicArr];
            }else{
                [mtbArr_2 addObjectsFromArray:dicArr];
            }
            
        }];
        [self.paraSectionArr removeAllObjects];
        [self.paraSectionArr addObject:mtbArr_1];
        [self.paraSectionArr addObject:mtbArr_2];
    }
}


#pragma mark ------ 参数设置 提交参数
- (void)devParamsSetFromNetwork{
    
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    NSMutableArray *deviceArr = [NSMutableArray array];
    if (self.syncArr.count>0) {
        [deviceArr addObjectsFromArray:self.syncArr];
    }else{
        [deviceArr addObject:self.deviceModel.deviceId];
    }
    
    [requestPara setObject:deviceArr forKey:@"deviceIds"];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":ValidNullData(self.endPointModel.sn)};
    [paraListArr addObject:endPointDic];
  
    //工作模式 0:自发自用 1:备电模式 2:PV全额上网模式 3:PV+Bat全额上网模式 4:VPP模式 5:TOU模式
    NSDictionary *modeDic = @{
        @"paramName": @"Inv5_Mode",
        @"regAddr" : @(4203),
        @"offset" : @(0),
        @"num" : @(16),
        @"dataType" : @"int",
        @"value" : @"4"

    };
    [paraListArr addObject:modeDic];
   //分组发送
    NSMutableArray *paraArr = [self.paraSectionArr safeObjectAtIndex:self.paraIndex];
    
    //要按寄存器从小到大排列下发
    [paraArr sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        if (obj1[@"regAddr"]&&obj2[@"regAddr"]) {
            if ([obj1[@"regAddr"] integerValue] < [obj2[@"regAddr"] integerValue]) {
                return NSOrderedAscending;
            }else if ([obj1[@"regAddr"] integerValue] > [obj2[@"regAddr"] integerValue]){
                return NSOrderedDescending;
            }else{
                return NSOrderedSame;
            }
            
        }else{
            return NSOrderedSame;
        }
    }];
    
    [paraListArr addObjectsFromArray:paraArr];
    
        

    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    self.hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"设置中...".rh_localized,self.paraIndex+1,self.paraSectionArr.count];
//    [QMUITips showLoading:[NSString stringWithFormat:@"%@(%ld/%ld)",@"设置中...".rh_localized,self.paraIndex+1,self.paraSectionArr.count] inView:self.navigationController.view];
    [BaseModel startWithCompletionAPIKey:H_deviceConfigSync argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        //参数发送完毕
        if (self.paraIndex == self.paraSectionArr.count-1) {
            [self.hud hideAnimated:NO];
            [QMUITips showSucceed:@"设置完成".rh_localized];
        }else{
            //发送下一组
            if ([self respondsToSelector:@selector(sendNextCmd)]) {
                [self performSelector:@selector(sendNextCmd) withObject:nil afterDelay:10];
            }
            
        }
        if([request.responseJSONObject[@"data"] isKindOfClass:[NSArray class]]){
            NSArray *failDevArr = request.responseJSONObject[@"data"];
            NSMutableString *mtbStr = [NSMutableString string];
            [failDevArr enumerateObjectsUsingBlock:^(NSString*  _Nonnull deviceId, NSUInteger idx, BOOL * _Nonnull stop) {
                [mtbStr appendString:deviceId];
                if (idx != failDevArr.count-1) {
                    [mtbStr appendString:@","];
                }
            }];
            [ProgressHUDManage showText:[NSString stringWithFormat:@"%@%@",mtbStr,@"设置失败".rh_localized]];
        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        //参数发送完毕
//        if (self.paraIndex == self.paraSectionArr.count-1) {
//
//        }else{
//            //等10秒再发送下一组,设备处理不过来
//            kWeakSelf;
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                weakSelf.paraIndex++;
//                [weakSelf devParamsSetFromNetwork];
//            });
//
//        }
    }];
}

-(void)sendNextCmd
{
    self.paraIndex++;
    [self devParamsSetFromNetwork];
}


#pragma mark ------ 时间校准 密码校验
-(void)setDateAction:(RHVppSetCommonModel*)model
{
    if (model.content.length == 0) {
        return;
    }
    if (Password_Check) {
        PasswordVerifyController *vc = [[PasswordVerifyController alloc] init];
        [[RHWindowTipManage shareWindowTipManage] showWithController:vc];
    
        kWeakSelf;
        vc.callBackBlock = ^(NSString * _Nonnull password) {
                    NSDictionary *dic = [RHTools getAccountInfo];
                    if ([SafeStr(dic[@"password"]) isEqualToString:password]) {
                        [weakSelf systemTimeVerity:model];
                    }else{
                        [QMUITips showInfo:@"密码错误".rh_localized];
                    }
        };
    }else{
        [self systemTimeVerity:model];
    }
         
}

#pragma mark ------ 时间校准
-(void)systemTimeVerity:(RHVppSetCommonModel*)model
{
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":ValidNullData(self.endPointModel.sn)};
    [paraListArr addObject:endPointDic];
  
    if (model.content.length>0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        formatter.dateFormat = @"yyyy/MM/dd HH:mm:ss";
        NSDate *date = [formatter dateFromString:model.content];
        [self processTimeParams:paraListArr date:date];
    }
    
    if (paraListArr.count == 0) {
        return;
    }
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamSetSingle",
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoading:@"设置中...".rh_localized inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"设置成功".rh_localized];
            
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

#pragma mark ------- 处理麦格瑞能时间校准格式
-(void)processTimeParams:(NSMutableArray*)paramList date:(NSDate*)date
{
    NSArray *keys = @[@"Inv3_RTCYear",@"Inv3_RTCMonth",@"Inv3_RTCDay",@"Inv3_RTCHour",@"Inv3_RTCMinute",@"Inv3_RTCSecond"];
    NSArray *value = @[@(date.year%100),@(date.month),@(date.day),@(date.hour),@(date.minute),@(date.second)];
    [keys enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSMutableDictionary *timeDic = [NSMutableDictionary dictionary];
        NSString *valueStr = [NSString stringWithFormat:@"%02ld",[value[idx] integerValue]];
        [timeDic setObject:@"int" forKey:@"dataType"];
        [timeDic setObject:keys[idx] forKey:@"paramName"];
        [timeDic setObject:valueStr forKey:@"value"];
        [timeDic setObject:@(1160+idx) forKey:@"regAddr"];//1160-1165
        [timeDic setObject:@(16) forKey:@"num"];
        [timeDic setObject:@(0) forKey:@"offset"];
        [paramList addObject:timeDic];
    }];
   
}
#pragma mark ------- 时间校准读取 (只读取6个字段)
-(void)readSystemTime:(RHVppSetCommonModel*)timeModel
{
    [self.view endEditing:YES];
    
    if(!self.endPointModel)return;
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":self.endPointModel.sn};
    [paraListArr addObject:endPointDic];
    //只读取时间校准的参数
    [self processTimeParams:paraListArr date:[NSDate new]];
    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamReadSingle",//只读取6个字段
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            [QMUITips showSucceed:@"读取完成".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self getParamStatusData];
            });
        }
        
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        [self.hud hideAnimated:YES];
    }];
}

#pragma mark ------- 设置参数成功的回读
-(void)readParamData
{
    [self.view endEditing:YES];
   
    //全读不用传参数
    if(!self.endPointModel)return;
//    if (self.paraSectionArr.count == 0) {
//        return;
//    }
    
    NSMutableDictionary *requestPara = [NSMutableDictionary dictionary];
    
    //参数的body
    NSMutableDictionary *bodyDic = [NSMutableDictionary dictionary];
    NSMutableArray *paraListArr = [NSMutableArray array];
    
    NSDictionary *endPointDic = @{@"dataType":@"string",
                                  @"paramName":@"sn",
                                  @"value":self.endPointModel.sn};
    [paraListArr addObject:endPointDic];
    
    //全读不用传参数
//    NSMutableArray *paraArr = [self.paraSectionArr safeObjectAtIndex:self.paraIndex];
//    [paraListArr addObjectsFromArray:paraArr];

    
    [bodyDic setObject:paraListArr forKey:@"commandParamList"];
    [requestPara setValue:bodyDic forKey:@"protocolBody"];
    
    //参数的头部
    NSString *randomStr = [NSString generateRandomLetter:15];
    NSTimeInterval interval = [[NSDate date] timeIntervalSince1970]*1000;
    NSDictionary *headContent = @{
        @"cmdId": randomStr,
        @"deviceId": self.deviceModel.deviceId,
        @"deviceType": self.deviceModel.productTypeCode,
        @"endpointCode":self.endPointModel.endpointCode,
        @"paramCount":@(paraListArr.count-1),
        @"sn":self.endPointModel.sn,
        @"messageType": @(1),//下行
        @"namespace": @"ParamReadAll",//全读
        @"payloadVersion": @(1),
        @"timestamp": @((NSInteger)interval)
      };
    [requestPara setValue:headContent forKey:@"protocolHead"];
    
    self.hud.label.text = [NSString stringWithFormat:@"%@",@"读取中...".rh_localized];
//    self.hud.label.text = [NSString stringWithFormat:@"%@(%ld/%ld)",@"读取中...".rh_localized,self.paraIndex+1,self.paraSectionArr.count];
//    [QMUITips showLoading:[NSString stringWithFormat:@"%@(%ld/%ld)",@"读取中...".rh_localized,self.paraIndex+1,self.paraSectionArr.count] inView:self.view];
    [BaseModel startWithCompletionAPIKey:H_controlDevice argument:requestPara requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 60054) {//设备不在线,停止下发
            [self.hud hideAnimated:NO];
            return;
        }
        //参数发送完毕
//        if (self.paraIndex == self.paraSectionArr.count-1) {
            [self.hud hideAnimated:NO];
        [QMUITips showSucceed:@"读取完成".rh_localized inView:self.view hideAfterDelay:1];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self getParamStatusData];
        });
           
//        }else{
//            //发送下一组
//            kWeakSelf;
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                weakSelf.paraIndex++;
//                [weakSelf readParamData];
//            });
//
//        }
       
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        [self.hud hideAnimated:YES];
    }];
    
}


-(UIView*)footerView{
    kWeakSelf;
    UIView *footer = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 80)];
    
    QMUIButton *commitBtn = [[QMUIButton alloc]init];
    [commitBtn setTitle:@"提交".rh_localized forState:UIControlStateNormal];
    [commitBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [commitBtn setCornerRadius:8];
    [commitBtn setBackgroundColor:CMainColorGreen];
    [footer addSubview:commitBtn];
    [commitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.height.offset(45);
        make.centerY.mas_offset(0);
    }];
    
    QMUIButton *readBtn = [[QMUIButton alloc]init];
    [readBtn setTitle:@"读取".rh_localized forState:UIControlStateNormal];
    [readBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [readBtn setCornerRadius:8];
    [readBtn setBackgroundColor:CMainColorGreen];
    [footer addSubview:readBtn];
    [readBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(commitBtn.mas_right).offset(15);
        make.right.mas_offset(-15);
        make.height.width.equalTo(commitBtn);
        make.centerY.equalTo(commitBtn);
    }];
    
    [[commitBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf checkParaEnableStatus];
    }];
    
    [[readBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        
//        [weakSelf createSectionReadPara];//全读不用传参数
        [weakSelf.hud hideAnimated:NO];
        [weakSelf showHud];
        [weakSelf readParamData];
    }];
    return footer;
}


-(void)showHud{
    if (self.navigationController.view==nil) {
        return;
    }
    _hud = [MBProgressHUD showHUDAddedTo:kAppWindow animated:YES];
    _hud.mode = MBProgressHUDModeIndeterminate;
    //不使用蒙版,使用背景颜色
    _hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    _hud.bezelView.backgroundColor = kColorRGBA(0, 0, 0,  0.8);
    _hud.bezelView.layer.cornerRadius = 8;
    _hud.bezelView.layer.masksToBounds = YES;
    //图片和文字的颜色
    _hud.contentColor = [UIColor whiteColor];
    _hud.removeFromSuperViewOnHide = YES;
    _hud.label.text = @"";
    // Configure the button.
    [_hud.button setTitle:@"取消".rh_localized forState:UIControlStateNormal];
    [_hud.button addTarget:self action:@selector(cancelWork:) forControlEvents:UIControlEventTouchUpInside];

}

-(void)cancelWork:(UIButton*)button
{
    [[NetworkAgent sharedAgent] cancelAllRequests];
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self.hud hideAnimated:YES];
   
}



@end
